<template>
  <basic-dialog v-model="dialogVisible" :autoClose="false"
                :submitBtnLoading="submitLoading" :title="'分解ERP传递的计划'" width="1000"
                @cancel="handlerCancel" @submit="handleSubmit" @close="handlerCancel">
    <avue-form
        ref="formProductRefs"
        v-model="form"
        :option="formOption">
    </avue-form>
    <avue-crud v-if="displayShowTable" ref="crudProductRefs" :data="tableData" :option="erpAddOption"
               @beforeOpen="beforeOpen"
               @row-save="rowSave"
               @row-update="rowUpdate"
               @row-del="rowDel">
      <template #menu-left="{row}">
        <el-button icon="el-icon-plus"
                   size="small"
                   type="primary"
                   @click="rowAdd(row)">
          新增
        </el-button>
      </template>
    </avue-crud>

    <basic-dialog v-model="selectAddVisible" :autoClose="false" title="选择ERP生产计划" width="1600"
                  @submit="submitDialog">
      <el-main style="height:calc(100vh - 200px)">
        <basic-crud ref="topCrudRef" :apiListParams="listTopPatrams" :option="selectTopOption"
                    apiGetListUrl="/mes/workRequestController/listCanUse" selectType="radio"
                    @current-row-change="handleCurrentRowChange">

        </basic-crud>
        <basic-crud ref="bottomCrudRef" :apiListParams="listBottomPatrams" :autoLoad="false"
                    :option="selectBottomOption"
                    businessUrl="mes/workRequestItemController"
                    selectType="radio"
                    style="margin-top: 10px" @current-row-change="handleCurrentBottomRowChange"
                    @selection-change="bottomSelectionChange"></basic-crud>
      </el-main>
    </basic-dialog>
  </basic-dialog>
</template>

<script setup>

import {computed} from "vue";
import {cloneDeep} from "lodash";
import {verifyNull} from "@/utils/validate";

const props = defineProps({
  submitSuccess: {
    type: Function,
    default: () => {
    },
  },
})

const emits = defineEmits(['AfterUploadSuccess'])

const erpAddOption = ref({
  addBtn: false,
  cellBtn: true,
  submitBtn: false,
  emptyBtn: false,
  index: true,
  editBtn: true,
  height: '280',
  column: [{
    prop: 'quantity',
    label: '本批次的数量',
    width: 130,
    labelWidth: "140",
    rules: [{
      required: true, message: "数量不能为空", trigger: "blur"
    }],
    min: 1,
    type: 'number',
    cell: true,
    change: (value) => value < 1 ? 1 : value
  }, {
    label: '本批次计划开始日期',
    prop: 'needStartDate',
    display: true,
    format: 'YYYY-MM-DD',
    labelWidth: "140",
    placeholder: '不输入默认使用表格上方的计划开工日期',
    type: 'date',
    cell: true
  },
    {
      label: '本批次计划完成日期',
      prop: 'needEndDate',
      display: true,
      format: 'YYYY-MM-DD',
      placeholder: '不输入默认使用表格上方的计划完工日期',
      labelWidth: "140",
      type: 'date',
      cell: true
    }]
});

const dialogVisible = ref(false);
const crudProductRefs = ref(null);
const openDialog = () => {
  dialogVisible.value = true;
};
const childForm = ref({});
const index = ref(1);
const tableData = ref([]);
const displayShowTable = ref(false);
//分解新增打开前
const beforeOpen = (done) => {
  if (form.value.code == null || form.value.code == '') {
    ElMessage.error("请先选择项目的内容");
    return false;
  }
  if (tableData.value && tableData.value.length > 0) {
    if (getBatchTotal() >= form.value.quantity) {
      ElMessage.error("已经分解完成了，不能继续分解了");
      return false;
    }
  }
  childForm.value.uuid = index.value;
  index.value = index.value + 1;
  done();
};
//分解计算总数
const getBatchTotal = () => {
  var total = 0;
  for (let i = 0; i < tableData.value.length; i++) {
    total += parseInt(tableData.value[i].quantity);
  }
  return total;
};
//分解新增
const rowAdd = () => {
  if (form.value.code == null || form.value.code == '') {
    ElMessage.error("请先选择项目的内容");
    return false;
  }
  if (tableData.value && tableData.value.length > 0) {
    if (getBatchTotal() >= form.value.unBlockQuantity) {
      ElMessage.error("已经分解完成了，不能继续分解了");
      return false;
    }
  }
  tableData.value.push({
    uuid: childForm.value.uuid,
    $cellEdit: true,
    quantity: 1,
    needStartDate: form.value.needStartDate,
    needEndDate: form.value.needEndDate
  });
};
//分解保存
const rowSave = (formSave, done, loadding) => {
  if (verifyNull(formSave.quantity) || formSave.quantity == 0) {
    ElMessage.error("请填写批次数量");
    loadding();
    return false;
  }
  if (getBatchTotal() > form.value.unBlockQuantity) {
    ElMessage.error("数量超过了计划要求的数量");
    loadding();
    return false;
  }
  done();
};
//分解编辑
const rowUpdate = (formSave, done) => {
  if (verifyNull(formSave.quantity) || formSave.quantity == 0) {
    ElMessage.error("请填写批次数量");
    done();
    return false;
  }
  tableData.value.forEach((val) => {
    if (val.uuid == form.uuid) {
      val = formSave;
    }
  });
  if (getBatchTotal() > form.value.unBlockQuantity) {
    ElMessage.error("各个批次的数量超过了计划要求的数量");
    done();
    return false;
  } else {
    done();
  }
};
//分解删除
const rowDel = (form) => {
  tableData.value.pop(form);
};
// 上方当前行数据
const currentRow = ref({});
const topCrudRef = ref(null);
const bottomCrudRef = ref(null);
const bottomRow = ref({});
// 上方表格行单击事件
const handleCurrentRowChange = (row) => {
  currentRow.value = row;
  topCrudRef.value?.setCurrentRowHandler(row);
};

const handleCurrentBottomRowChange = (row) => {
  bottomRow.value = row;
  bottomCrudRef.value?.setCurrentRowHandler(row);
}

const userInfo = JSON.parse(localStorage.getItem('userInfo'));
// 上方表格参数
const listTopPatrams = computed(() => {
  return {
    orderBy: 'code',
    orderMethod: 'asc',
    integrationFlag: true,
    zeRenDeptId: userInfo?.deptGroupId
  }
});
// 下方表格参数
const listBottomPatrams = computed(() => {
  return {
    orderBy: 'planDeliveryDate',
    orderMethod: 'asc',
    workRequestId: currentRow.value?.id,
    status: 'Editing,partUsed',
    zeRenDeptId: userInfo?.deptGroupId
  }
});
const bottomHeight = ref((document.body.clientHeight - 200) * 0.45 - 65);
const selectAddVisible = ref(false);
const selectTopOption = ref({
  highlightCurrentRow: true,
  size: 'small',
  addBtn: false,
  menu: false,
  calcHeight: bottomHeight.value + 180,
  column: [
    {
      label: "状态",
      prop: "status",
      width: 100,
      display: false,
      align: "center",
      statusShow: true,
      statusTag: true,
      statusTypeMap: {
        Editing: 'info',
        Released: 'success',
        Obsoleted: 'danger',
      },
    },
    {
      label: "计划编号",
      prop: "code",
      sortable: true,
      overHidden: true,
      searchSpan: 6,
      search: true,
      align: "center",
      width: 220,
    },
    {
      label: "项目名称",
      prop: "name",
      sortable: true,
      searchSpan: 6,
      overHidden: true,
      search: true,
    },
    {
      label: "生产计划审批单名称",
      prop: "planAuditOrderName",
      sortable: true,
      searchSpan: 6,
      overHidden: true,
      search: true,
      searchLabelWidth: 160,
    },
    {
      label: "来源名称",
      prop: "planSourceName",
      searchSpan: 6,
      search: true,
      overHidden: true,
    },
    {
      label: "来源编号",
      prop: "planSourceCode",
      overHidden: true,
    },
    {
      label: "年度",
      prop: "yearNum",
    },
    {
      label: "紧急程度",
      prop: "exigencyLevel",
      type: "select",
      dicData: [
        {
          label: "不紧急",
          value: "none",
        },
        {
          label: "一般",
          value: "normal",
        },
        {
          label: "紧急",
          value: "exigency",
        },
        {
          label: "非常紧急",
          value: "veryExigency",
        },
      ],
    },
    {
      label: "军检",
      prop: "armyCheck",
      width: 50,
      type: "switch",
      align: 'center',
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }
      ]
    }]
});
const selectBottomOption = ref({
  highlightCurrentRow: true,
  size: 'small',
  addBtn: false,
  menu: false,
  header: false,
  height: bottomHeight.value,
  column: [
    {
      label: '项目号',
      prop: 'code',
      overHidden: true,
      display: false,
    }, {
      label: '产品名称',
      prop: 'productName',
      overHidden: true,
      display: false
    }, {
      label: '产品型号',
      prop: 'modelName',
      overHidden: true,
      display: false
    }, {
      label: '数量',
      prop: 'quantity',
      overHidden: true,
      display: false
    }, {
      label: '已分解/未分解数量',
      prop: 'planQuantity',
      type: 'number',
      width: 130,
      formatter: (val) => {
        if (val.planQuantity == null) {
          val.planQuantity = 0;
        }
        return val.planQuantity + "/" + (val.quantity - val.planQuantity);
      }
    }, {
      label: "责任部门",
      prop: 'zeRenDeptName',
      overHidden: true,
    }, {
      label: '甲方投产函号',
      prop: 'produceCode',
      overHidden: true,
    }, {
      label: '计划开工日期',
      prop: 'planBeginDate',
      display: false,
      type: 'date'
    }, {
      label: '计划完工日期',
      prop: 'planFinishDate',
      display: false,
      format: 'yyyy-MM-dd',
      type: 'date'
    }, {
      label: '计划交付日期',
      prop: 'planDeliveryDate',
      display: false,
      format: 'yyyy-MM-dd',
      type: 'date'
    }, {
      label: '批次号',
      prop: 'batchNum',
      display: false,
      overHidden: true,
    }, {
      label: '配套机型',
      prop: 'targetModel',
      display: false,
      overHidden: true,
    }
  ]
});
const validateDate = (rule, value, callback) => {
  const needEndDate = new Date(value).getTime();
  const planDeliveryDate = new Date(form.value.planDeliveryDate).getTime();
  if (value === '') {
    callback(new Error('计划完成日期不能为空'));
  } else if (needEndDate > planDeliveryDate) {
    callback(new Error('计划完成日期晚于计划交付日期!'));
  } else {
    callback();
  }
};

const status = computed(() => {
  return form.value.planDeliveryDate ? true : false;
});
const form = ref({});
const formOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: true,
  labelWidth: 120,
  column: [
    {
      label: "ERP项目号",
      prop: "code",
      type: "input",
      gutter: 32,
      span: 12,
      readOnly: true,
      labelWidth: "140",
      formslot: true,
      rules: [
        {
          required: true,
          message: "请务必选择ERP计划信息",
          trigger: "change",
        },
      ],
      append: '选择ERP计划',
      click: () => {
        selectAddVisible.value = true;
      },
      appendClick: () => {
        selectAddVisible.value = true;
      }
    },
    {
      label: '计划开始日期',
      prop: 'needStartDate',
      format: 'yyyy-MM-dd',
      labelWidth: "140",
      rules: [{required: true, message: "计划开始日期必须输入", trigger: "blur"}],
      type: 'date'
    },
    {
      label: '计划完成日期',
      prop: 'needEndDate',
      labelWidth: "140",
      type: 'date',
      rules: [
        {required: true, validator: validateDate, trigger: "blur"},
      ],
    },
    {
      label: "配套机型",
      prop: "targetModel",
      labelWidth: "140",
      component: 'BasicCrudTableSelect',
      width: 150,
      comProps: {
        saveFieldMap: {targetModel: 'name'},
        comType: 'form',
      },
      crudProps: {
        apiReferUrl: '/mes/mesApplyProductController/referGrid',
        option: {
          menu: false,
          column: [
            {prop: 'name', label: '机型名称'},
            {prop: 'orderNum', label: '排序号'}
          ]
        }
      },
      curForm: form,
      change: (newV) => {
        form.value = newV;
        formProductRefs.value?.clearValidate();
      },
      rules: [
        {
          required: true,
          message: "请选择配套机型",
          trigger: "blur",
        },
      ],
    },
    {
      labelWidth: 140,
      prop: 'batchFlag',
      label: '是否按批分解',
      type: 'switch',
      value: 'false',
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
      change: (val) => {
        displayShowTable.value = val.value === 'true';
      }
      // control: (column) => {
      //   if (column === 'true') {
      //     vm.$data.openBatchInfo = true;
      //   } else {
      //     vm.$data.openBatchInfo = false;
      //   }
      // }
    },
    {
      label: "军检",
      prop: "armyCheck",
      labelWidth: "140",
      width: 90,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
      value: 'false'
    },
    {
      label: '数量',
      prop: 'quantity',
      labelWidth: "140",
      disabled: true
    },
    {
      label: '已分解数量',
      prop: 'planQuantity',
      labelWidth: "140",
      disabled: true
    },
    {
      label: '未分解数量',
      prop: 'unBlockQuantity',
      labelWidth: "140",
      disabled: true
    },
    {
      label: '计划交付日期',
      prop: 'planDeliveryDate',
      labelWidth: "140",
      disabled: true
    }
  ]
});

//ERP项目号 参照确认
const submitDialog = () => {
  if (!bottomRow.value || Object.keys(bottomRow.value).length === 0) {
    ElMessage.error('请选择数据!');
    return false;
  }
  const {
    id,
    code,
    targetModel,
    planBeginDate: needStartDate,
    planFinishDate: needEndDate,
    planDeliveryDate,
    quantity,
    planQuantity = 0 // 默认值为0
  } = bottomRow.value;
  Object.assign(form.value, {
    requestItemId: id,
    code,
    targetModel,
    needStartDate,
    needEndDate,
    planDeliveryDate,
    quantity,
    planQuantity: Math.max(planQuantity, 0), // 确保不小于0
    unBlockQuantity: quantity - Math.max(planQuantity, 0)
  });
  selectAddVisible.value = false;
}


const submitLoading = ref(false)
const formProductRefs = ref()
// 保存确认按钮触发
const handleSubmit = async () => {
  await formProductRefs.value.validate()
  submitLoading.value = true
  ElMessage.success('保存成功！')
  props.submitSuccess && props.submitSuccess()
  handlerCancel();
}
const handlerCancel = async () => {
  await formProductRefs.value.resetFields();
  dialogVisible.value = false;
  form.value = {};
};

defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>

</style>
